package com.khyr.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.khyr.Dao.OrderDao;
import com.khyr.Service.OrderService;
import com.khyr.entity.HisOrderCharge;
import com.khyr.vo.R;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class MyRabbitListener {
    //把收到的消息封装到一个Message对象中

        @Autowired
        private OrderDao orderDao;

        @Autowired
        private OrderService orderService;

        @RabbitListener(queues = "delayed.queue") //监听正常队列1分钟
        public void fund(Message message, Channel channel) {
            try {
                //判断微信的支付状态
                R<Map> mapR = orderService.queryPayStatus(new String(message.getBody()));
                if (mapR.getCode() == 200) {
                    //从正常队列删除该消息
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
                } else {
                    Thread.sleep(1000);//1秒
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
                }
            } catch (Exception e) {
                throw new AmqpRejectAndDontRequeueException(e.getMessage());
            }
        }


        @RabbitListener(queues = "dead.letter.queue") //监听死信队列
        public void dlxQueueMessage(Message message, Channel channel) {
            // byte[] body = message.getBody();
            String orderId = new String(message.getBody());
            QueryWrapper wrapper = new QueryWrapper<>();
            wrapper.eq("order_id", orderId);
            HisOrderCharge hisOrderCharge = orderDao.selectOne(wrapper);//根据订单id查询数据库中订单状态
            if (hisOrderCharge != null) {
                // 查询订单的支付状态
                if ("0".equals(hisOrderCharge.getOrderStatus()+"")) {
                    // 将订单状态设置成已超时
                    hisOrderCharge.setOrderStatus("1"); //超市
                    this.orderDao.updateById(hisOrderCharge);
                    //修改库存数量
                }
                try {
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }



    }




}